package com.kc.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class ResponesBean {
    //状态码
    private int code;

    //返回的信息
    private String msg;

    //返回的数据
    private Object data;

    @Override
    public String toString() {
        return "{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public ResponesBean(int code, String msg, Object object) {
        this.code = code;
        this.msg = msg;
        this.data = object;
    }

    public ResponesBean() {
        super();
    }
    public void setAll(int code,String msg,Object data){
        this.code=code;
        this.msg=msg;
        this.data=data;

    }

    public void responseError(ServletRequest request, ServletResponse response, int code, String content, String data) throws IOException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        this.code=code;
        this.msg=content;
        this.data = data== null ? null : data;
        httpServletResponse.setStatus(code);

        PrintWriter writer = httpServletResponse.getWriter();
        ObjectMapper objectMapper = new ObjectMapper();
        writer.write(objectMapper.writeValueAsString(this.toString()));
        writer.flush();
        writer.close();

    }
}